package com.itheima.xx.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Description:
 *
 * @author codermao
 * @date 2023/10/25 15:03
 */
public class SqlSessionUtil1 {
    private static SqlSessionFactory factory;

    static {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        try (
                //读取核心配置文件
//                InputStream is = Resources.getResourceAsStream("mybatis-config.xml")
                InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
        ) {
            //创建工厂对象
            factory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return 返回会话对象，自动提交事务
     */
    public static SqlSession getSession() {
        return factory.openSession(true);
    }

    /**
     * @param isAutoCommit 是否自动提交事务
     * @return 会话对象
     */
    public static SqlSession getSession(boolean isAutoCommit) {
        return factory.openSession(isAutoCommit);
    }

    /**
     * 提交事务并关闭session
     * @param session
     */
    public static void commitAndClose(SqlSession session){
        if (session!=null){
            session.commit();
            session.close();
        }
    }

    /**
     * 回滚事物并关闭session
     * @param session
     */
    public static void rollbackAndClose(SqlSession session){
        if (session != null){
            session.rollback();
            session.close();
        }
    }

}
